package com.motong.gongdan.util;

import org.apache.commons.io.FileUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.UUID;

/**
 * @author:fff
 * @time:2022/5/27
 */
public class FileUtil {

    public static String uploadFile(MultipartFile file, String path) {
        //获取文件后缀
        String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1);
        File savePathFile = new File(path);
        if (!savePathFile.exists()) {
            //若不存在该目录，则创建目录
            savePathFile.mkdir();
        }
        String filename = UUID.randomUUID().toString().replaceAll("-", "") + "." + suffix;
        try {
            FileUtils.copyInputStreamToFile(file.getInputStream(), new File(path + filename));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return path.replace("/service", "") + filename;
    }


    public static String uploadFile(MultipartFile file, String path, String fileNamePrefix) {
        //获取文件后缀
        String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
        File savePathFile = new File(path);
        if (!savePathFile.exists()) {
            //若不存在该目录，则创建目录
            savePathFile.mkdir();
        }
        String filename = fileNamePrefix + suffix;
        try {
            FileUtils.copyInputStreamToFile(file.getInputStream(), new File(path + filename));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return path + filename;
    }
}
